package com.llan;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

/**
 * hystrix 快速失败
 * @author java_long
 * @create 2018/5/23 11:32
 **/
public class HystrixFailsFast extends HystrixCommand<String> {

    private final boolean throwException;

    public HystrixFailsFast(boolean throwException) {
        super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
        this.throwException = throwException;
    }

    @Override
    protected String run() {
        if (throwException) {
            throw new RuntimeException("failure from HystrixFailsFast");
        } else {
            return "success";
        }
    }

    public static class UnitTest {

        @Test
        public void testSuccess() {
            assertEquals("success", new HystrixFailsFast(false).execute());
        }

        @Test
        public void testFailure() {
            try {
                new HystrixFailsFast(true).execute();
                fail("we should have thrown an exception");
            } catch (HystrixRuntimeException e) {
                assertEquals("failure from HystrixFailsFast", e.getCause().getMessage());
                e.printStackTrace();
            }
        }
    }
}
